package com.tcc.fastline.Fragments;

import java.util.ArrayList;
import java.util.List;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.tcc.fastline.ConstantesAplicacao;
import com.tcc.fastline.FastLineActivity;
import com.tcc.fastline.SessionManager;
import com.tcc.fastline.BLL.BLLFactory;
import com.tcc.fastline.BLL.interfaces.IEstabelecimentoBS;
import com.tcc.fastline.Domain.*;
import com.tcc.fastline.Exceptions.ValidationServerException;
import com.tcc.fastline.Helpers.BuilderHelper;
import com.tcc.fastline.Helpers.GridViewEstabelecimentoAdapter;
import com.tcc.fastline.Helpers.NavigationHelper;
import com.tcc.fastline.Helpers.ProgressHelper;
import com.tcc.smartqueue.R;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ConsultaEstabelecimentoFragment extends ConteudoFragment
{
	private ProgressDialog dialog;
	private Handler handler;
	private SessionManager session;
	private View _view;
	private Context context;

	private GridViewEstabelecimentoAdapter adapterGridViewEstabelecimento;
	private ArrayAdapter<String> adapter = null;

	private TextView textEmpty;
	private PullToRefreshGridView listViewUsuarios = null;
	private GridView mGridView;
	private AutoCompleteTextView autoComplete = null;
	private List<Estabelecimento> listaEstabelecimentos;

	IEstabelecimentoBS estabelecimentosBS = null;

	@Override
	public ConteudoFragment newInstance(Bundle argumentsBundle)
	{
		return newInstance();
	}

	@Override
	public ConteudoFragment newInstance()
	{
		ConsultaEstabelecimentoFragment newFragment = new ConsultaEstabelecimentoFragment();

		Bundle argumentsBundle = new Bundle();

		newFragment.setArguments(argumentsBundle);

		return newFragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{

		View rootView = inflater.inflate(R.layout.consulta_estabelecimento_fragment, null);

		context = rootView.getContext();
		_view = rootView.findViewById(R.id.consulta_estabelecimento);
		handler = new Handler();
		dialog = ProgressDialog.show(context, "", "Por favor aguarde...", false, false);

		IniciarSessao();

		IniciarCamadasDeNegocio();

		InitializeFields(rootView);

		new Thread()
		{
			public void run()
			{
				try
				{
					listaEstabelecimentos = ObterEstabelecimentos();
					handler.post(new Runnable()
					{
						@Override
						public void run()
						{
							popularAutoCompleteTela(listaEstabelecimentos);
							PopularGridEstabelecimentos(listaEstabelecimentos);
						}
					});
				}
				catch (ValidationServerException e)
				{
					ExibirValidationServerException(e.getMessage());
					e.printStackTrace();
				}
				catch (Exception e)
				{
					ExibirValidationServerException(e.getMessage());
					e.printStackTrace();
				}
				finally{
					dialog.dismiss();
				}
			}
		}.start();
		return rootView;
	}

	private void IniciarSessao()
	{
		this.session = new SessionManager(context);
	}

	private void IniciarCamadasDeNegocio()
	{
		estabelecimentosBS = BLLFactory.getEstabelecimentoBS(context);
	}

	private void InitializeFields(View rootView)
	{
		IniciarAutoComplete(rootView);

		IniciarGridEstabelecimentos(rootView);
	}

	private void IniciarAutoComplete(View rootView)
	{
		autoComplete = (AutoCompleteTextView) rootView.findViewById(R.id.autoComplete);
		autoComplete.setThreshold(1);

		autoComplete.setOnItemClickListener(new OnItemClickListener()
		{

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
			{
				String texto = (String) arg0.getItemAtPosition(arg2);

				List<Estabelecimento> estabelecimentos = filtrarListaEstabelecimentosParaEstabelecimentoSelecionado(texto);

				PopularGridEstabelecimentos(estabelecimentos);
			}

			private List<Estabelecimento> filtrarListaEstabelecimentosParaEstabelecimentoSelecionado(
					String texto)
			{
				List<Estabelecimento> estabelecimentos = new ArrayList<Estabelecimento>();

				for (Estabelecimento estabelecimento : listaEstabelecimentos)
				{
					if (estabelecimento.getNome().equals(texto))
					{
						estabelecimentos.add(estabelecimento);
					}
				}
				return estabelecimentos;
			}
		});
	}

	private void IniciarGridEstabelecimentos(View rootView)
	{
		listViewUsuarios = (PullToRefreshGridView) rootView.findViewById(R.id.pull_refresh_grid);
		textEmpty = (TextView) rootView.findViewById(android.R.id.empty);
		mGridView = listViewUsuarios.getRefreshableView();

		mGridView.setEmptyView(textEmpty);
		mGridView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		mGridView.setBackgroundColor(Color.WHITE);
		mGridView.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> adp, View v, int position, long arg3)
			{
				Estabelecimento estabelecimentoSelecionado = (Estabelecimento) adp
						.getItemAtPosition(position);
				Log.e("Estab selecionado",
						estabelecimentoSelecionado != null ? estabelecimentoSelecionado.getNome() : "NULO");

				session.setKeySession(ConstantesAplicacao.CHAVE_PESQUISA_ESTABELECIMENTO,
						estabelecimentoSelecionado);

				NavigationHelper.exibirPagina(R.layout.estabelecimento_view);
			}
		});

		listViewUsuarios.setOnRefreshListener(new OnRefreshListener<GridView>()
		{
			@Override
			public void onRefresh(PullToRefreshBase<GridView> refreshView)
			{

				try
				{
					final List<Estabelecimento> estabelecimentos = ObterEstabelecimentos();

					PopularGridEstabelecimentos(estabelecimentos);
					popularAutoCompleteTela(estabelecimentos);

				}
				catch (ValidationServerException e)
				{
					e.printStackTrace();
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
				finally
				{
					listViewUsuarios.onRefreshComplete();
				}

			}
		});

	}

	private List<Estabelecimento> ObterEstabelecimentos() throws ValidationServerException, Exception
	{
		List<Estabelecimento> estabelecimentos = new ArrayList<Estabelecimento>();

		estabelecimentos = estabelecimentosBS.BuscarEstabelecimentos();

		return estabelecimentos;
	}

	private void ExibirValidationServerException(String mensagem)
	{
		BuilderHelper.OK("Erro", mensagem, context, new OnClickListener()
		{

			@Override
			public void onClick(DialogInterface dialog, int which)
			{

			}
		});
	}

	private void popularAutoCompleteTela(List<Estabelecimento> listEst)
	{
		List<String> listaEstabelecimento = transformarListaEstabelecimentoParaString(listEst);

		adapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, listaEstabelecimento);

		autoComplete.setAdapter(adapter);
		adapter.notifyDataSetChanged();
	}

	private List<String> transformarListaEstabelecimentoParaString(List<Estabelecimento> listEst)
	{
		List<String> listaEstabelecimento = new ArrayList<String>();

		for (Estabelecimento estabeleciemento : listEst)
		{
			listaEstabelecimento.add(estabeleciemento.getNome());
		}
		return listaEstabelecimento;
	}

	private void PopularGridEstabelecimentos(List<Estabelecimento> listEst)
	{
		adapterGridViewEstabelecimento = new GridViewEstabelecimentoAdapter(getActivity(), listEst);
		mGridView.setAdapter(adapterGridViewEstabelecimento);
		adapterGridViewEstabelecimento.notifyDataSetChanged();
	}
}
